<?php
// +----------------------------------------------------------------------
// | 在线投票管理
// +----------------------------------------------------------------------
// | @link ( http://www.yurnero.net )
// +----------------------------------------------------------------------
// | @copyright
// +----------------------------------------------------------------------
// | @licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | @author Haijun Wu <nicholasinlove@126.com>
// +----------------------------------------------------------------------
// | $Id: VoteAction.class.php 49 2011-02-27 10:31:09Z nicholasinlove1986@gmail.com $
// +----------------------------------------------------------------------


class VoteAction extends BaseAction {

	public function index() {
		redirect(__APP__);
	}
	
	public function listVote() {
		//排序字段 默认为主键
		if (isset($_REQUEST ['order'])) {
			$order = $_REQUEST ['order'];
		} else {
			$order = 'vote_id';
		}
		//排序方式 默认按照倒序排列
		if (isset($_REQUEST ['sort'])) {
			$sort = $_REQUEST ['sort'];
		} else {
			$sort = 'desc';
		}
		//查询过滤
		$map  =	 array();	
	
		switch($_REQUEST['map']) {
			case 'visible':  $map['vote_visible'] = 0; break;		
			case 'status': $map['vote_status'] = 0; break;
        }		
			
		if ($_REQUEST['keyword']!='') {
			$map['vote_name'] = array('like',"%{$_REQUEST['keyword']}%");
		}
		
		$vote  =  M ('Vote');
		import("@.ORG.Page");
		C ( 'PAGE_ROLLPAGE',C('page_roll') );
		$count = $vote->where($map)->count();
		$p = new Page ($count, C('admin_list_num'));
		$list = $vote->where($map)->field(C('DB_PREFIX').'admin_user.user_name,'.C('DB_PREFIX').'vote.*')->join(C('DB_PREFIX').'admin_user ON '.C('DB_PREFIX').'admin_user.user_id = '.C('DB_PREFIX').'vote.user_id')->order("`".$order."` ".$sort)->limit($p->firstRow.','.$p->listRows)->findAll();
		$p->setConfig('theme',C('admin_page_theme'));
		//分页跳转的时候保证查询条件
		foreach ($map as $key => $val) {
			if (!is_array ($val)) {
				$p->parameter .= "$key=" . urlencode ( $val ) . "&";
			}
		}
		$page = $p->show ();
		
		$this->assign('action_link', array('href'=>__URL__.'/addVote/', 'text' => '添加投票'));
		$this->assign('ur_here','投票列表');
		$this->assign('pagestyle',C('admin_page_style'));	
		$this->assign('page', $page);
		$this->assign('list',$list);
		$this->assign('sort',$sort);
		$this->display();
	}
	
	public function addVote() {
		$this->assign('action_link', array('href'=>__URL__.'/listVote/', 'text' => '投票列表'));
		$this->assign('ur_here','添加投票');
		$this->assign('userId',$_SESSION[C('USER_AUTH_KEY')]);
		$this->assign('vote_starttime',gmtime());
		$this->assign('vote_endtime',gmtime()+3600*24*31);
		$this->display();
	}
	
	public function insertVote() {
		if ($_REQUEST['act']) {	
			$vote = D('Vote');
			if (!$vote->create()) {
				$this->error($vote->getError());
			} else {
				if ($result = $vote->add()) {
					clear_cache_files();    // 清除缓存
					set_log('add(Vote, Id: '.$result.')');
					$this->assign('jumpUrl',__URL__.'/listOption/id/'.$result);
					$this->success('添加投票主题成功');
				} else {
					$this->error('操作失败');
				}
			}
		} else {
			$this->error('非法操作');
		}	
	}
	
	public function editVote() {
		$vote = M('Vote');
		$vo	  =	$vote->getByVoteId($_REQUEST['id']);
		$this->assign('vo',$vo);
		$this->assign('action_link', array('href'=>__URL__.'/listVote/', 'text' => '投票列表'));
		$this->assign('ur_here','编辑投票');
		$this->display();
	}
	
	public function updateVote() {
		$vote = D('Vote');
		if (!$vote->create()) {
			$this->error($vote->getError());
		} else {
			/*简单的数据一致性检查*/
			if ($vote->vote_status != false) {				
				$vo   = M ('VoteOption');
				$list = $vo->where('vote_id ='.$vote->vote_id)->findAll();
				$count = $vo->where('vote_id ='.$vote->vote_id)->count();
				/*主题下是否有选项(单选,多选)*/
				if ($list[0]['vote_id'] == '') {
					$this->assign('jumpUrl',__URL__.'/listOption/id/'.$vote->vote_id);
					$this->error('您需要为投票主题添加选项');
				}
				/*主题下是否2个选项以上*/
				if ($count == 1) {
					$this->assign('jumpUrl',__URL__.'/listOption/id/'.$vote->vote_id);
					$this->error('您需要为投票主题: '.$vote->vote_name.' 添加2个选项以上');	
				}
			}
			$result = $vote->save();
			if (false !== $result) {
				clear_cache_files();    // 清除缓存
				set_log('edit(Vote, Id: '.$vote->vote_id.')');
				$this->assign('jumpUrl',__URL__.'/listVote/');
				$this->success('投票信息修改成功');
			} else {
				$this->error('操作失败');
			}
		}
	}
	
	public function listOption() {
		//排序字段 默认为主键
		if (isset($_REQUEST ['order'])) {
			$order = $_REQUEST ['order'];
		} else {
			$order = 'option_sort';
		}
		//排序方式 默认按照倒序排列
		if (isset($_REQUEST ['sort'])) {
			$sort = $_REQUEST ['sort'];
		} else {
			$sort = 'desc';
		}
		
		$vote_id = $_REQUEST['id'];
		
		$vo  =  M ('VoteOption');
		$vote = M ('Vote');
		$vote_name = $vote->where('vote_id ='.$vote_id)->getField('vote_name');
		$list = $vo->where('vote_id ='.$vote_id)->order("`".$order."` ".$sort)->findAll();
		
		$this->assign('action_link', array('href'=>__URL__.'/listVote/', 'text' => '投票列表'));
		$this->assign('ur_here','投票选项列表 [ '.$vote_name.' ]');
		$this->assign('list',$list);
		$this->assign('vote_id',$vote_id);
		$this->assign('sort',$sort);
		$this->display();
	}
	
	public function newOption() {
		if ($_REQUEST['act']) {
			/* 处理选项跟链接地址 */
			$option  = $_POST['option_name'];
			$option  = str_replace('，', ',', $option);
			$option  = str_replace(',,', ',', $option);	
			$option  = explode(',',$option);
			$vote_id = $_POST['id'];
			if (!empty($option)) {
				$vo  =  M ('VoteOption');
				$map = array();
				$map['vote_id'] = $vote_id;
				$map['option_name'] = $option[0];
				$vote_name = $vo->where($map)->getField('option_name');
				if ($vote_name == $option[0]) {
					$this->error('此投票选项已经存在');
				} else {
					$max_sort = $vo->where('vote_id ='.$vote_id)->max('option_sort');
					$option_sort = empty($max_sort) ? 1 : $max_sort+1;
					$data['vote_id']      = $vote_id;
					$data['option_name']  = $option[0];
					$data['option_url']   = $option[1];
					$data['option_count'] = 0;
					$data['option_sort']  = $option_sort;
					$vo_id = $vo->add($data);
					set_log('add(Vote, Option, Id: '.$vo_id.')');
					$this->success('添加成功');
				}	
			} else {
				$this->error('必须输入投票选项名称');
			}
		} else {
			$this->error('非法操作');
		}	
	}
	
	//选项排序,为何要独立出来,是这样设置比较清晰,使用ajax有点乱	
	public function sortOption() {
		if ($_REQUEST['act']) {	
			$vo = M('VoteOption');
			$pk = $vo->getPk();
			foreach($_POST['key'] as $key => $val) {
				$list = $vo->where("$pk = $key")->setField('option_sort', $val);
			}
			if ($list!==false) {
				set_log('edit(Vote, Option, Sort)');
				$this->assign('jumpUrl',__URL__.'/listOption/id/'.$_REQUEST['vote_id']);
				$this->success ('操作成功' );
			} else {
				$this->error ('操作失败');
			}
		} else {
			$this->error ('非法操作');
		}
	}
	
	//ajax编辑选项的信息
	public function editOption() {
		$vo = M('VoteOption');
		if ($_REQUEST['act'] == 'option_name') {
			$option_id = $_REQUEST['id'];
			$option_name = $_REQUEST['value'];
			$vote_id = $vo->where("option_id = $option_id")->getField('vote_id');
			$map = array();
			$map['vote_id'] = $vote_id;
			$map['option_name'] = $option_name;
			$vote_name = $vo->where($map)->getField('option_name');
			if ($vote_name == $option_name) {
				$this->error('此投票选项已经存在');
			} else {		
				$list = $vo->where("option_id = $option_id")->setField('option_name', $option_name);
				if ($list!==false) {
					set_log('edit(Vote, Option, Name)');
					$this->success ('操作成功');
				} else {
					$this->error ('操作失败');
				}
			}
		} elseif ($_REQUEST['act'] == 'option_count') {
			$option_id = $_REQUEST['id'];
			$option_count = $_REQUEST['value'];
			$list = $vo->where("option_id = $option_id")->setField('option_count', $option_count);
			if ($list!==false) {
				set_log('edit(Vote, Option, Count)');
				$this->success ('操作成功');
			} else {
				$this->error ('操作失败');
			}
		} elseif ($_REQUEST['act'] == 'option_url') {
			$option_id = $_REQUEST['id'];
			$option_url = $_REQUEST['value'];
			$list = $vo->where("option_id = $option_id")->setField('option_url', $option_url);
			if ($list!==false) {
				set_log('edit(Vote, Option, Url)');
				$this->success ('操作成功');
			} else {
				$this->error ('操作失败');
			}
		}

	}
	
	//删除选项
	public function dropOption() {
		$vo = M('VoteOption');
		$vote = M ('Vote');
		$map['option_id']	 =	$_REQUEST['id'];
		$list = $vo->where($map)->delete();
		/*简单的数据一致性检查*/			
		$count = $vo->where('vote_id ='.$_REQUEST['v'])->count();
		/*主题下是否2个选项以上*/
		if ($count < 2) {
			$vote->where('vote_id ='.$_REQUEST['v'])->setField('vote_status', 0);
		}
		if ($list!==false) {
			set_log('drop(Vote, Option)');
			redirect(__URL__.'/listOption/id/'.$_REQUEST['v']);
		} else {
			$this->error ('操作失败');
		}
	}
	
	public function initializeVote() {
		$vo   = M ('VoteOption');
		$vote = M ('Vote');
		$vp   = M ('VoteIp');
		$vote_id = $_REQUEST['id'];		
		/*所有选项置零*/
		$vo->where("vote_id = $vote_id")->setField('option_count', 0);		
		/*投票人数置零*/
		$vote->where("vote_id = $vote_id")->setField('vote_count', 0);		
		/*ip*/
		$vp->where("vote_id = $vote_id")->delete();
		set_log('initialize(Vote)');
		$this->success ('成功清空数据');   
	}
	
	public function dropVote() {
		$vo   = M ('VoteOption');
		$vote = M ('Vote');
		$vp   = M ('VoteIp');
		$pk   =  $vote->getPk();
		$condition = array ($pk => array ('in', $_POST['key']));
		$vo->where($condition)->delete();
		$vote->where($condition)->delete();
		$vp->where($condition)->delete();
		set_log('drop(Vote)');
		redirect(__URL__.'/listVote/');
	}
	
	public function viewVote() {
		$id = $_REQUEST['id'];
		$vote = get_vote($id);
		C ('SHOW_RUN_TIME', false);
		C ('SHOW_PAGE_TRACE', false);
		$this->assign('vote',$vote['content']);
		$this->display();
	}

}

?>